<template>
  <div>
    <h3>{{ isNew?'创建课程':"编辑课程" }}</h3>
    <ele-form :form-data="data" :form-desc="fields" :request-fn="submit" />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';

@Component({})
export default class extends Vue {
  @Prop(String) id!: string;

  data = {};
  fields = {
    name: { label: '课程名称', type: 'input' },
    cover: { label: '课程封面', type: 'input' },
  };

  async fetch() {
    const { data } = await this.$http.get(`course/${this.id}`);
    this.data = data;
  }

  async submit(data: any) {
    const url = this.isNew ? 'course' : `course/${this.id}`;
    const method = this.isNew ? 'post' : 'put';
    await this.$http[method](url, data);
    this.data = {};
    this.$message.success('创建成功');
    this.$router.go(-1);
  }

  created() {
    !this.isNew && this.fetch();
  }

  get isNew() {
    return !this.id;
  }
}
</script>